#include "seqlist.h"
#include <stdarg.h>
#include <stdio.h>

seqlist* create_list(unsigned capicity) {
    seqlist* list = (seqlist*)malloc(sizeof(seqlist) + sizeof(int) * capicity);
    if (NULL == list) {
        return NULL;
    }
    list->capicity = capicity;
    list->length   = 0;
    return list;
}

void free_list(seqlist* list) {
    assert(list != NULL);
    free(list->data);
    free(list);
}

void visit_list(seqlist* list, void (*callback)(int)) {
    assert(list != NULL);
    for (int i = 0; i < list->length; i++) {
        callback(list->data[i]);
    }
}

/**
 * NOTE 可以不考虑扩容，假定容量足够大
 */
seqlist* insert(seqlist* list, int* p, int val) {
    assert(list != NULL);
    // 在最后一个元素后面插入的情形
    if (p == list->data[list->length - 1]) {
        list->data[list->length] = val;
        list->length++;
        return list;
    }
    // 移动元素，给新元素让出位置
    // TODO 由学员补齐此处的逻辑(已完成)
    for(int* least = list->data +list->length;least < p;least--)
    {
        *least = *(least - 1);
    }

    *p = val;
    list->length++;
    

    return list;
}

void remove(seqlist* list, int* p) {
    assert(list != NULL);
    // 移除最后一个元素的情形
    if (p == list->data[list->length - 1]) {
        list->length--;
        return ;
    }
    // 移动元素
    // TODO 由学员补齐此处的逻辑
    if(p < list->data || p > list->data + list->length){
        return;
    }
    for(int* least = p;least < list->data + list->length - 1;)
    {
        *(least) = *(least + 1);
    }
    list->length--;
    return;
    
}

